package com.basic.contraller;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;


import java.io.File;
import java.io.IOException;

public class LuceneManager {
    /*
    *索引维护
    * 添加
    * 修改
    * 删除
    * 查询  Lucene中
    * */

    @Test
//    创建索引
    public void testIndex() throws  Exception{
//        1.创建一个indexWrite对象
//        1）指定索引库的存放位置Directory对象
//        2）指定一个分析器，对文档内容进行分析
        Directory directory = FSDirectory.open(new File("D:\\temp\\index"));
//       官方推荐
        Analyzer analyzer = new IKAnalyzer();
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LATEST,analyzer);
        IndexWriter indexWriter =new IndexWriter(directory,indexWriterConfig);


//        3.创建field对象将filed添加到document对象中
        File f = new File("D:\\Lucene\\searchsource");
        File[] listFiles = f.listFiles();
        for (File file:listFiles) {
            //        2.创建document对象
            Document document = new Document();
//            文件名称
            String file_name = file.getName();
            Field fileNameField = new TextField("fileName",file_name, Field.Store.YES);
//            文件大小
            long file_size = FileUtils.sizeOf(file);
            Field fileSizeField = new LongField("fileSize",file_size, Field.Store.YES);
//            文件路径
            String file_path = file.getPath();
            Field filePathField = new StoredField("filePath",file_path);
//            文件内容
            String file_content=  FileUtils.readFileToString(file);
            Field fileContentField = new TextField("fileContent",file_content, Field.Store.YES);
            document.add(fileNameField);
            document.add(fileSizeField);
            document.add(filePathField);
            document.add(fileContentField);
//        4.使用indexWriter对象将document对象写入索引库，此过程进行索引创建，并将索引和document对象写入索引库
            indexWriter.addDocument(document);
        }
//        5.关闭indexWriter对象
        indexWriter.close();
    }

 public IndexWriter getIndexWriter() throws IOException {
     Directory directory = FSDirectory.open(new File("D:\\temp\\index"));
//       官方推荐
     Analyzer analyzer = new StandardAnalyzer();
     IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LATEST,analyzer);
     return new IndexWriter(directory,indexWriterConfig);
 }
    @Test
    /*全删除*/
    public void LuceneALLDelete ()throws Exception{
        IndexWriter indexWriter =  getIndexWriter();
        indexWriter.deleteAll();
        indexWriter.close();
    }
    /*根据条件删除*/
    @Test
    public void LuceneDelete ()throws Exception{
        IndexWriter indexWriter =  getIndexWriter();
        Query query = new TermQuery(new Term("fileName","tomcat"));
        indexWriter.deleteDocuments(query);
        indexWriter.close();
    }
    /*修改*/
    @Test
    public void LuceneUpdate ()throws Exception{
        IndexWriter indexWriter =  getIndexWriter();
        Document doc =new Document();
        doc.add(new TextField("fileName","测试文件名", Field.Store.YES));
        doc.add(new TextField("fileContent","测试文件内容", Field.Store.YES));
       indexWriter.updateDocument(new Term("fileName","tomcat"),doc,new IKAnalyzer());
        indexWriter.close();
    }
    /*索引库查询
    * 查询所有
    * */
    public IndexSearcher getIndexSearcher() throws Exception {
        //1.创建directory对象 -索引库存放的位置-硬盘上的库
        Directory directory = FSDirectory.open(new File("D:\\temp\\index"));
        //        Directory directory1 =new RAMDirectory();内存索引库
//2.创建一个indexReader对象 需要指定indexReader对象
        IndexReader indexReader = DirectoryReader.open(directory);
        //3.创建一个indexSearch对象需要指定indexReader对象
        return  new IndexSearcher(indexReader);
    }

//    执行查询的结果
    public  void printResult(IndexSearcher indexSearcher, Query query) throws Exception{
//        执行查询
        TopDocs topDocs =  indexSearcher.search(query,20);
//        返回查询解果
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc:scoreDocs) {
            int doc =scoreDoc.doc;
            Document document = indexSearcher.doc(doc);
//            文件名称
            String fileName = document.get("fileName");
//            文件内容
            String fileContent = document.get("fileContent");
//            文件路径
            String fileSize = document.get("fileSize");
//            文件大小
            String filePath = document.get("filePath");

            System.out.println("文件名称: "+fileName+"文件路径: "+filePath+"文件大小: "+fileSize);
            System.out.println("---------------------------------------------------------------------");
        }
    }

    //    查询所有 渲染结果
    @Test
    public void LuceneSearchAll () throws  Exception{
        IndexSearcher indexSearcher = getIndexSearcher();
        Query query = new MatchAllDocsQuery();
        printResult(indexSearcher,query);
//        关闭
        indexSearcher.getIndexReader().close();

    }

//    精准查询
    @Test
public void   NumericRangeQuery () throws  Exception{
    IndexSearcher indexSearcher = getIndexSearcher();
    Query query = NumericRangeQuery.newLongRange("fileSize",1000L,2000L,true,true);
    printResult(indexSearcher,query);
//        关闭
    indexSearcher.getIndexReader().close();

}
//组合查询
    @Test
    public void   BooleanQuery () throws  Exception{
        IndexSearcher indexSearcher = getIndexSearcher();
        BooleanQuery booleanQuery = new BooleanQuery();
        Query query1 = new TermQuery(new Term("fileName","apache"));
        Query query2 = new TermQuery(new Term("fileName","lucene"));
        booleanQuery.add(query1, BooleanClause.Occur.MUST);
        booleanQuery.add(query2, BooleanClause.Occur.MUST);
        printResult(indexSearcher,booleanQuery);
//        关闭
        indexSearcher.getIndexReader().close();

    }
//    条件解析的对象查询
    @Test
    public void   QueryParser () throws  Exception{
        IndexSearcher indexSearcher = getIndexSearcher();
//        默认查询的域 参数1：默认域 参数2 分析器
        QueryParser queryParse = new QueryParser("fileName",new IKAnalyzer());
//        *:*查询所有 *：域 *：值  参数1 :查找的域 参数2 :要查找的值
        Query query = queryParse.parse("fileContent:lucene");
//        范围查询

        printResult(indexSearcher,query);
        indexSearcher.getIndexReader().close();
    }
    @Test
//条件解析对象查询 多个默认域
    public void   MultiFieldQueryParser () throws  Exception{

        IndexSearcher indexSearcher = getIndexSearcher();
        String[] fields={"fileName","fileContent"};
//        默认查询的域 参数1：默认域 参数2 分析器
        MultiFieldQueryParser queryParser = new MultiFieldQueryParser(fields,new IKAnalyzer());
//        *:*查询所有 *：域 *：值  参数1 :查找的域 参数2 :要查找的值
        Query query = queryParser.parse("lucene");
//        范围查询

        printResult(indexSearcher,query);
        indexSearcher.getIndexReader().close();


    }
}
